#include "apue.h"
#include <pthread.h>

static int quitflag;
sigset_t mask;

pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc= PTHREAD_COND_INITIALIZER;

void * thr_fn(void *arg) {
    int err, signo; 
    while (1) {
        err= sigwait(&mask, &signo);
        if (err > 0)
            err_exit(err, "sigwait error");
        switch (signo) {
            case SIGINT:
                printf("interrupt\n");
                break;
            case SIGQUIT:
                pthread_mutex_lock(&lock);
                quitflag= 1;
                pthread_cond_signal(&waitloc);
                pthread_mutex_unlock(&lock);
                return ((void *)0);
                break;
            default:
                err_quit("invalid signo %d", signo);
        }
    }
    return ((void *)0);
}

int main(void) {
    int err;
    sigset_t oset;
    pthread_t tid;

    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGQUIT);
    if ((err= pthread_sigmask(SIG_BLOCK, &mask, &oset)) != 0)
        err_exit(err, "pthread_sigmask error");

    if ((err= pthread_create(&tid, NULL, &thr_fn, 0)) != 0) 
        err_exit(err, "pthread_create error");
    
    pthread_mutex_lock(&lock);
    while (quitflag == 0)
        pthread_cond_wait(&waitloc, &lock);
    pthread_mutex_unlock(&lock);

    quitflag= 0;
    pthread_sigmask(SIG_SETMASK, &oset, NULL);
    return(0);
}
